import * as echarts from '../../ec-canvas/echarts';
var baseConfig = require("../../baseConfig");
var http = require("../../utils/http.js")
// const app = getApp();

function initChart1(chart, xdata, ydata) {
  var option = {
    title: {
      text: '',
      left: 'center',
    },
    color: ["#fff"],
    legend: {
      data: ['A'],
      top: 50,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xdata,
      minorSplitLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    dataZoom: [{
      show: true,
      type: 'inside',
      filterMode: 'none',
      xAxisIndex: [0],
      startValue: 0,
      endValue: 15
    }, ],
    series: [{
      type: 'line',
      data: ydata
    }]
  };
  chart.setOption(option);
}

function initChart2(chart, xdata, ydata) {
  var option = {
    title: {
      text: '',
      left: 'center',
    },
    color: ["#fff"],
    legend: {
      data: ['A'],
      top: 50,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xdata,
      minorSplitLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLabel: {
        color: "#fff"
      },
      axisLine: {
        lineStyle: {
          color: "#fff"
        }
      }
    },
    dataZoom: [{
      show: true,
      type: 'inside',
      filterMode: 'none',
      xAxisIndex: [0],
      startValue: 0,
      endValue: 15
    }, ],
    series: [{
      type: 'line',
      data: ydata
    }]
  };
  chart.setOption(option);
}

const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatTimeTwo(number, format) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}

Page({
  data: {
    productInfo: {
      appGoodsSimpleInfos: []
    },
    is_weixin: 0,
    selectedProductList: [],
    selectTime: formatTimeTwo(Date.parse(new Date()), 'Y-M-D'),
    date: formatTimeTwo(Date.parse(new Date()), 'Y-M-D'),
    show: false,
    ec1: {
      lazyLoad: true
    },
    ec2: {
      lazyLoad: true
    },
    minDate: new Date().getTime() - 24 * 60 * 60 * 1000 * (formatTimeTwo(Date.parse(new Date()), 'Y-M-D').split("-")[2] - 1),
    maxDate: new Date().getTime(),
    earningsDataSumMap: {},
    earningsDataMap: {},
    ecpmDataMap: {},
    layer0TextPopup: false,
    layer1TextPopup: false,
    layer2TextPopup: false,
    layer3TextPopup: false,
    layer1Popup: false,
    layer2Popup: false,
    layer3Popup: false,
    layer4Popup: false,
    extendTitle: "",
    more: true,
    page: 0
  },
  onLoad: function (options) {
    console.log("options111111:", options)
    if(options.appId == '28') {
      this.setData({
        appType: 'cpm'
      })
    } else if(options.appId == '29') {
      this.setData({
        appType: 'cps'
      })
    }
    this.setData({
      total: options.total,
      productInfo: options,
      totalElements: options.totalElements,
      // selectedProductList: JSON.parse(decodeURIComponent(options.appGoodsSimpleInfos))
    })
    // console.log(this.data.selectedProductList);
    this.getProductId()
    this.bindLoadingmore()
  },
  onReady: function () {
    this.getData()
    this.oneComponent = this.selectComponent('#mychart-one');
    this.twoComponent = this.selectComponent('#mychart-two');
    // console.log(this.oneComponent);
  },
  onShow: function () {
    this.getData()
  },
  testImg(e) {
    let {
      appid,
      goodsid,
      name,
      test_icon,
      test_name,
      logo
    } = e.currentTarget.dataset;
    // console.log('test_name', test_name, 'test_icon', test_icon, 'logo', logo, 'name', name, 'goodsid', goodsid, 'appid', appid);
    wx.navigateTo({
      url: '/pages/testImg/testImg?appid=' + appid +
        '&logo=' + logo +
        '&goodsId=' + goodsid +
        '&name=' + name +
        '&test_icon=' + test_icon +
        '&test_name=' + test_name,
    })
  },
  reloadClick() {
    this.getData()
  },
  selectTimeClick(e) {
    this.setData({
      date: e.detail.value
    })
    this.getData()
  },
  onDisplay() {
    this.setData({
      show: true
    });
  },
  closeYesClick() {
    this.setData({
      layer4Popup: false
    })
  },
  yesClick() {
    this.setData({
      layer4Popup: true
    })
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  formatDate(date) {
    date = new Date(date);
    var year = `${date.getFullYear()}`
    var month = `${date.getMonth() + 1}`
    var dated = `${date.getDate()}`
    if (month < 10) {
      month = "0" + month
    }
    if (dated < 10) {
      dated = "0" + dated
    }
    return `${year}-${month}-${dated}`;
  },
  CPMClick() {
    this.setData({
      layer1TextPopup: true
    })
  },
  CPMClick1() {
    this.setData({
      layer0TextPopup: true
    })
  },
  closeClick1() {
    this.setData({
      layer0TextPopup: false,
      layer1TextPopup: false,
    })
  },
  adClick() {
    this.setData({
      layer2TextPopup: true
    })
  },
  closeClick2() {
    this.setData({
      layer2TextPopup: false
    })
  },
  ecpmClick() {
    this.setData({
      layer3TextPopup: true
    })
  },
  closeClick3() {
    this.setData({
      layer3TextPopup: false,
      layer3Popup: false
    })
  },
  douyinDownClick() {
    wx.request({
      url: baseConfig.baseUrl + `qrcode/tt/${this.data.productInfo.appId}`,
      method: "GET",
      data: {
        is_weixin: 0,
        goodsId: 0
      },
      header: {
        "Authorization": wx.getStorageSync('token'),
        "UID": wx.getStorageSync('userid'),
        'Content-Type': 'application/json'
      },
      success: res => {
        this.setData({
          layer1Popup: true
        })
        this.setData({
          imgUrl: res.data.data
        })
      }
    })
  },
  douyinDownClick1(e) {
    wx.request({
      url: baseConfig.baseUrl + `qrcode/tt/${this.data.productInfo.appId}`,
      method: "GET",
      data: {
        is_weixin: 0,
        goodsId: e.currentTarget.dataset.id
      },
      header: {
        "Authorization": wx.getStorageSync('token'),
        "UID": wx.getStorageSync('userid'),
        'Content-Type': 'application/json'
      },
      success: res => {
        this.setData({
          layer1Popup: true
        })
        this.setData({
          imgUrl: res.data.data
        })
      }
    })
  },
  bindLoadingmore: function () {
    var that = this
    http.reqLoading("get_goods_page", {
      appId: this.data.productInfo.appId,
      p: this.data.page,
      f: 5
    }, res => {
      // console.log("tuandui===", JSON.stringify(res))
      that.setData({
        totalElements: res.data.totalElements,
      })
      if (res.data.content && res.data.content.length == 5) {
        that.data.selectedProductList = that.data.selectedProductList.concat(res.data.content)
        this.data.page = this.data.page + 1
        that.setData({
          selectedProductList: that.data.selectedProductList
        })
      } else if ((res.data.content && res.data.content.length > 0)) {
        this.data.page = this.data.page + 1
        that.data.selectedProductList = that.data.selectedProductList.concat(res.data.content)
        that.setData({
          more: false,
          selectedProductList: that.data.selectedProductList
        })
      }

    })
  },
  douYinCloseClick() {
    this.setData({
      layer1Popup: false
    })
  },
  saveImage(filePath) {
    var aa = wx.getFileSystemManager();
    aa.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/test.png',
      data: this.data.imgUrl,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/test.png',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: function (err) {
            console.log(err)
          }
        })
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  showToast(title) {
    wx.showToast({
      title: title
    });
  },
  saveImageToPhotos(filePath) {
    console.log(filePath);
    let self = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              self.saveImage(filePath)
              self.isGetSet = true
            },
            fail() {
              self.isGetSet = false
            }
          })
        } else {
          self.isGetSet = true
          self.saveImage(filePath)
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  savePhotoToAlbum(res) {
    this.saveImageToPhotos(res)
  },
  weixinDownClick(e) {
    var goodsId;
    var uid = wx.getStorageSync("userid")
    if (this.data.productInfo.appGoodsSimpleInfos.length == 0) {
      goodsId = 0
    } else {
      goodsId = 0
    }
    wx.request({
      url: baseConfig.baseUrl + `qrcode/tt/${this.data.productInfo.appId}`,
      method: "GET",
      data: {
        is_weixin: 1,
        uid: uid,
        dyAppId: this.data.productInfo.appId,
        goodsId: goodsId,
        title: this.data.productInfo.name
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: res => {
        this.setData({
          copyLinkData: res.data.data,
          layer2Popup: true,
          extendTitle: this.data.productInfo.name
        })
      }
    })
  },
  weixinDownClick1(e) {
    var name = e.currentTarget.dataset.name
    var goodsId;
    var uid = wx.getStorageSync("userid")
    if (this.data.productInfo.appGoodsSimpleInfos.length == 0) {
      goodsId = 0
    } else {
      goodsId = e.currentTarget.dataset.id
    }
    wx.request({
      url: baseConfig.baseUrl + `qrcode/tt/${this.data.productInfo.appId}`,
      method: "GET",
      data: {
        is_weixin: 1,
        uid: uid,
        dyAppId: this.data.productInfo.appId,
        goodsId: goodsId,
        title: name
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: res => {
        this.setData({
          copyLinkData: res.data.data,
          layer2Popup: true,
          extendTitle: name
        })
      }
    })
  },
  copyLinkClick() {
    wx.showToast({
      title: '复制成功',
    })
    wx.setClipboardData({
      data: this.data.copyLinkData,
      success: function (res) {
        wx.getClipboardData({
          success: (res) => {
            console.log(res.data)
          }
        })
      }
    })
  },
  iconClick() {
    this.setData({
      layer4Popup: true
    })
  },
  closeClick() {
    this.setData({
      layer1Popup: false,
      layer2Popup: false,
      layer4Popup: false,
    })
  },
  editClick() {
    this.setData({
      layer3Popup: true
    })
    this.setData({
      extendTitle1: ''
    })
  },
  inputValue(e) {
    console.log(e.detail.value)
    this.setData({
      extendTitle1: e.detail.value
    })
  },
  confirmClick() {
    var appId = wx.getStorageSync('appId')
    if (this.data.extendTitle1.length >= 10) {
      wx.showToast({
        title: '不超过10个字',
      })
      return
    }
    wx.request({
      url: `${baseConfig.url}/job_feign/msg_sec_check?appId=${appId}`,
      method: 'POST',
      data: {
        content: this.updateContent.extendTitle
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: response => {
        if (response.data.data.check == true) {
          var goodsId;
          var uid = wx.getStorageSync("userid")
          if (this.data.productInfo.appGoodsSimpleInfos.length == 0) {
            goodsId = 0
          } else {
            goodsId = ''
          }
          wx.request({
            url: baseConfig.baseUrl + `qrcode/tt/${this.data.productInfo.appId}`,
            method: "GET",
            data: {
              is_weixin: 1,
              uid: uid,
              dyAppId: this.data.productInfo.appId,
              goodsId: goodsId,
              title: this.data.extendTitle1
            },
            header: {
              'Content-Type': 'application/json'
            },
            success: res => {
              this.setData({
                copyLinkData: res.data.data,
                layer2Popup: true,
                layer3Popup: false,
                extendTitle: this.data.extendTitle1
              })
              wx.showModal({
                title: "推广标题已更改，请再次复制链接"
              })
            }
          })
        }
      }
    })
  },
  jiaochengClick() {
    wx.navigateTo({
      url: '/pages/problem/problem',
    })
  },
  closeClick4() {
    this.setData({
      layer4Popup: false
    })
  },
  getProductId() {
    wx.request({
      url: `${baseConfig.url}/baseSelect/mini_app_select`,
      method: 'POST',
      data: {
        is_weixin: 0 //"1":微信   "0":抖音
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        this.setData({
          array2: res.data.data
        })
        // console.log(this.data.array2[0].value)
        this.setData({
          appId: this.data.array2[0].value
        })
        this.getData()
      }
    })
  },
  init_one(xdata, ydata) { //初始化第一个图表
    this.oneComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      initChart1(chart, xdata, ydata)
      this.chart = chart;
      return chart;
    });
  },
  init_two(xdata, ydata) { //初始化第二个图表
    this.twoComponent.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      initChart2(chart, xdata, ydata)
      this.chart = chart;
      return chart;
    });
  },
  getData() {
    var openid = wx.getStorageSync('openid');
    var uid = wx.getStorageSync("userid");
    if (openid != undefined) {
      wx.request({
        url: `${baseConfig.url}/tuiwaApp/get_earnings_data_sum_for_app`,
        method: 'POST',
        data: {
          start_time: this.data.date,
          end_time: this.data.selectTime,
          appId: this.data.productInfo.appId,
          loginUserId: openid,
          uid: uid,
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: res => {
          console.log(res.data.data);
          this.setData({
            earningsDataSumMap: res.data.data.earningsDataSumMap,
            earningsDataMap: res.data.data.earningsDataMap,
            ecpmDataMap: res.data.data.ecpmDataMap
          })

          var initChart1OptionXAxisData = res.data.data.earningsDataMap.earningsDateList
          var initChart1OptionSeriesData = res.data.data.earningsDataMap.earningsValueList
          // console.log(initChart1OptionXAxisData, initChart1OptionSeriesData);
          this.init_one(initChart1OptionXAxisData, initChart1OptionSeriesData)

          var initChart2OptionXAxisData = res.data.data.ecpmDataMap.ecpmDateList
          var initChart2OptionSeriesData = res.data.data.ecpmDataMap.ecpmValueList
          this.init_two(initChart2OptionXAxisData, initChart2OptionSeriesData)
        }
      })
    }
  },
  yesClick1() {
    this.setData({
      layer6Popup: true
    })
  },
  closeYesClick() {
    this.setData({
      layer4Popup: false,
      layer6Popup: false,
    })
  },
})